package com.lu.search.interceptor;


import com.lu.model.user.pojo.ApUser;
import com.lu.utils.thread.ApUserSearchThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Optional;

@Slf4j
public class ApUserSearchInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String userId = request.getHeader("userId");
        Optional<String> optional = Optional.ofNullable(userId);
        if (optional.isPresent()) {
            //把用户存入threadlocal中
            ApUser apUser = new ApUser();
            apUser.setId(Integer.valueOf(userId));
            ApUserSearchThreadLocalUtil.setAppUser(apUser);
            log.info("存入的用户是{}", apUser);
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("清理了{}用户", ApUserSearchThreadLocalUtil.getAppUser());
        ApUserSearchThreadLocalUtil.remove();
    }
}
